<template>
<div id="wrapper">
  <nav-bar>
      <router-link class="navbar-item title" to="/settings">
          Settings
      </router-link>
  </nav-bar>
  <main>
    <card-search  @will-search="doSearch"></card-search>
    <card-list :cards="cards"></card-list>
  </main>
</div>
</template>

<script>
import CardList from '@/components/CardList'
import CardSearch from '@/components/CardSearch'
import NavBar from '@/components/NavBar'

export default {
  name: 'search-page',
  components: {
    CardSearch,
    CardList,
    NavBar
  },
  data: function () {
    return {
      cards: []
    }
  },
  created: function () {
  },
  mounted: function () {
    this.loadTop3()
  },
  computed: {
  },
  methods: {
    loadTop3: function () {
      const vm = this
      this.$db.cards.find({}, { _id: 0 }).limit(3).exec(function (err, docs) {
        if (err) {
          console.log(err)
          docs = []
        }
        vm.cards = docs
      })
    },
    doSearch (toSearch, inField) {
      if (toSearch === '') return
      const regex = RegExp('^' + toSearch)
      const doc = {}
      doc[inField] = {
        '$regex': regex
      }
      const vm = this
      this.$db.cards.find(doc, { _id: 0 }).exec(function (err, docs) {
        if (err) {
          console.log(err)
          docs = []
        }
        vm.cards = docs
      })
    }
  }
}
</script>

<style>

</style>
